package org

import (
	"d-serv-go/server/core/bean"
	"d-serv-go/server/core/consts"
	"d-serv-go/server/core/db"
	strutils "d-serv-go/server/core/util/stringutils"
)

//var OrgMgr = NewOrgMgr()

type orgMgr struct {
}

func NewOrgMgr() *orgMgr {
	return &orgMgr{}
}

func (o *orgMgr) CheckServAuth(servDef bean.Bean) bool {

	return false
}

func (o *orgMgr) GetCmpy(cmpyCode string) *bean.CmpyBean {
	cmpy, _ := db.ServDao.FindById(consts.SY_ORG_CMPY, cmpyCode, false)
	if cmpy == nil {
		panic(db.Ctx().GetSyMsg("SY_CMPY_NOT_FOUND", cmpyCode))
	}
	return &bean.CmpyBean{
		Bean: *cmpy,
	}
}

func (o *orgMgr) GetDeptNames(dept *bean.DeptBean) string {
	str := strutils.NewStringBuilder("")
	str.Append(dept.GetName())

	if dept.GetType() != consts.DEPT_TYPE_ORG && len(dept.GetPcode()) > 0 {
		// 取父部门名称
		parentDept := o.GetDept(dept.GetPcode())

		//是否遍历到最顶层节点
		if parentDept != nil {
			str.Append("/" + o.GetDeptNames(parentDept))
		}
	}

	return str.ToString()
}

func (o *orgMgr) GetDept(deptCode string) *bean.DeptBean {
	dept, _ := db.ServDao.FindById(consts.SY_ORG_DEPT, deptCode, false)
	if dept != nil {
		return &bean.DeptBean{
			Bean: *dept,
		}
	} else {
		return nil
	}
}


func (o *orgMgr) GetFullDeptNames(deptCode string) string{
	return o.GetDeptNames(o.GetDept(deptCode))
}

func (o *orgMgr) GetODeptBean(deptCode string) *bean.DeptBean{
	d := o.GetDept(deptCode)
	odeptCode := d.GetODeptCode()
	if odeptCode == d.GetCode() { //自身为机构部门
		return d
	} else {
		return db.OrgMgr.GetDept(odeptCode)
	}
}
func (o *orgMgr) GetTDeptBean(deptCode string) *bean.DeptBean{
	d := o.GetDept(deptCode)
	tdeptCode := d.GetTDeptCode()
	if tdeptCode == d.GetCode() { //自身为有效部门
		return d
	} else {
		return db.OrgMgr.GetDept(tdeptCode)
	}
}
func (o *orgMgr) GetParentDeptBean(deptCode string) *bean.DeptBean{
	d := o.GetDept(deptCode)
	if d.IsEmpty("DEPT_PCODE") {
		return nil
	}

	return db.OrgMgr.GetDept(d.GetStr("DEPT_PCODE"))
}

func (o *orgMgr) GetCmpyBean(cmpyCode string) *bean.CmpyBean{
	return o.GetCmpy(cmpyCode)
}
